package handler

import (
	"github.com/gin-gonic/gin"
	"liao/api/request"
	"liao/glodal"
	"liao/inits"
	"liao/model"
	"liao/pkg"
	"net/http"
	"strconv"
)

func Login(context *gin.Context) {
	var req request.Login
	if err := context.ShouldBind(&req); err != nil {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "参数失败",
		})
		return
	}
	get := glodal.Rdb.Get(inits.Ctx, "sendSms:"+req.Mobile)
	if get.Val() != req.SendSms {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "短信验证码错误",
		})
		return
	}
	num, _ := glodal.Rdb.Get(inits.Ctx, "User:"+req.Mobile).Int()
	if num >= 1 {
		context.JSON(http.StatusBadRequest, gin.H{
			"code":    http.StatusBadRequest,
			"message": "一个用户同时只能登录一个设备",
		})
		return
	}
	var user model.User
	glodal.DB.Where("mobile = ?", req.Mobile).First(&user)
	if user.ID == 0 {
		m := model.User{
			Mobile: req.Mobile,
			Passwd: pkg.MD5(req.Password),
		}
		glodal.DB.Create(&m)
	} else {
		if user.Passwd != pkg.MD5(req.Password) {
			context.JSON(http.StatusBadRequest, gin.H{
				"code":    http.StatusBadRequest,
				"message": "登录失败",
			})
			return
		}
	}
	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return
	}
	glodal.Rdb.Incr(inits.Ctx, "User:"+req.Mobile)
	context.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    handler,
	})
}
